package com.lthlearn.util;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: 2942733239@qq.com
 * @date: 2024/11/5 14:58
 * @description: com.lthlearn.util
 * @version: 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getParameter("token");
        if ("null".equals(token) || token == null) {
            // 用户未登录，重定向到登录页
            response.sendRedirect(request.getContextPath() + "/views/login.html");
            // 拦截
            return false;
        }
        // 如果传入的是一个非法的 token, 此处的 claims 是 null
        Claims claims = JWTUtils.checkJWT(token);
        if (claims == null) {
            // 用户未登录，重定向到登录页
            response.sendRedirect(request.getContextPath() + "/views/login.html");
            // 拦截
            return false;
        }
        // 放行
        return true;
    }
}
